package com.jd.org.controller;

import com.jd.basic.util.AjaxResult;
import com.jd.basic.util.PageList;
import com.jd.org.domain.Department;
import com.jd.org.service.DepartmentService;
import com.jd.org.query.DepartmentQuery;
import com.jd.system.annotation.PreAuthorize;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
@Api(value = "部门接口类",description = "部门接口类")
@RestController
@RequestMapping("/department")
public class DepartmentController {

    @Autowired
    private DepartmentService departmentService;

    @ApiOperation(value = "查询单个数据")
    @GetMapping("/{id}")
    public Department loadById(@PathVariable("id")Long id) {
        return departmentService.loadById(id);
    }

    @ApiOperation(value = "查询全部数据")
    @GetMapping
    public List<Department> findAll() {
        return departmentService.loadAll();
    }

    @ApiOperation(value = "删除数据")
    @DeleteMapping("/{id}")
    @PreAuthorize(name = "部门删除",sn = "department:delete")
    public AjaxResult remove(@PathVariable("id")Long id) {
        try {
            departmentService.del(id);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new AjaxResult(false,"删除失败");
    }

    @ApiOperation(value = "添加或修改数据")
    @PutMapping
    public AjaxResult addOrUpdate(@RequestBody Department department) {
        try {
            if (department.getId() == null) {
                departmentService.save(department);
            }else {
                departmentService.update(department);
            }
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new AjaxResult(false,"操作失败");
    }

    @ApiOperation(value = "高级查询")
    @PostMapping
    @PreAuthorize(name = "部门分页",sn = "department:list")
    public PageList<Department> find(@RequestBody DepartmentQuery departmentQuery) {
        return departmentService.queryPage(departmentQuery);
    }

    @ApiOperation(value = "批量删除数据")
    @PatchMapping
    public AjaxResult patchRemove(@RequestBody List<Long> ids) {
        try {
            departmentService.patchRemove(ids);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new AjaxResult(false,"批量除失败");
    }

    @ApiOperation(value = "查询部门树")
    @GetMapping("/deptTree")
    public List<Department> deptTree() {
        return departmentService.deptTree();
    }
}
